import sqlite3

from Tap import Tap
import numpy as np


class TapWith:
    def __init__(self, tap, dis):
        self.tap: Tap = tap
        self.dis: float = dis
        # print(tap.category, tap.img, tap.des, tap.vec, dis)


def iniDB():
    import sqlite3
    conn = sqlite3.connect("manyTaps.db")
    print("DB init success")
    conn.execute("""
    CREATE TABLE IF NOT EXISTS taps(
        category TEXT PRIMARY KEY,
        img TEXT NOT NULL,
        des TEXT NOT NULL,
        vec TEXT NOT NULL)
    """)
    print("TABLE taps init success")
    conn.commit()
    conn.close()
    pass


def insertTap(tap: Tap) -> bool:
    conn = sqlite3.connect("manyTaps.db")
    cur = conn.cursor()

    sql = f"REPLACE INTO taps(category, img, des, vec) \
                    VALUES ('{tap.category}', '{tap.img}', '{tap.des}', '{tap.getVec()}')"
    cur.execute(sql)

    conn.commit()
    conn.close()
    return True


def getVec2Ndarray(str1: str) -> np.ndarray:
    # print(str1)
    vec2 = np.array([float(x) for x in str1.split(',')])
    return vec2


def cmp(tapwith: TapWith):
    return tapwith.dis


def batchGetTaps(svec: np.ndarray, cnt: int) -> list:
    conn = sqlite3.connect("manyTaps.db")
    cur = conn.cursor()
    sql = f"SELECT * FROM taps WHERE vec"
    cur.execute(sql)
    list1 = []
    for row in cur:
        tap = Tap(row[0], row[1], row[2], getVec2Ndarray(row[3]))
        list1.append(TapWith(tap, tap.getDis(svec)))
    list1.sort(key=cmp)
    conn.close()
    # print("________________________")
    return list1[:cnt]

